<?php
namespace App\Actions;

use App\Models\AdminUser;
use App\Models\Department;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class DdbHookAction extends DyHookAction
{
    public $model;
    public $admin_user;

    public function __construct(Model $model = null, AdminUser $adminUser = null)
    {
        parent::__construct($model, $adminUser);
    }

    /**
     * 党代表数据
     */
    public function import($all_datas, $table, $dzb, $yjdzz)
    {
        foreach($all_datas as $_data) {
            # 判断数据是否重复
            $_data['dzb'] = $dzb;
            $_data['yjdzz'] = $yjdzz;
            $_data['dwmc'] = $this->admin_user->ddb_dwmc;
            $_data['dwdm'] = $this->admin_user->ddb_dwdm;
            $_data['updated_by_gid'] = $this->admin_user->gid;
            $_data['updated_at'] = date("Y-m-d H:i:s");
            if (!isset($_data['name']) || !$_data['name']) {
                continue;
            }
            $dwdm = $this->admin_user->ddb_dwdm;
            if ($_data['name'] && $model = DB::table($table)->where('name', $_data['name'])->where('dwdm', $dwdm)->first()) {
                DB::table($table)->where('name', $_data['name'])->where('dwdm', $dwdm)->update($_data);
                $id = $model->id;
            } else {
                $_data['created_by_gid'] = $this->admin_user->gid;
                $_data['created_at'] = date("Y-m-d H:i:s");
                $id = DB::table($table)->insertGetId($_data);
            }
            $relation_row = DB::table($table)->where('id', $id)->first();
            $this->updateDdbMainRow($relation_row, $table);
        }
    }

    /**
     * 更新党代表的主要数据
     */
    public function updateDdbMainRow($relation_row, $relation_table)
    {
        if (!$relation_row) {
            return;
        }
        if (!$relation_row->name) {
            return;
        }
        $sums = DB::table($relation_table)->where('name', $relation_row->name)
        ->select(DB::raw('sum(dps) as zdps, sum(dys) as zdys'))->first();
        $zdps = 0; # 总提名支部数
        $zdys = 0; # 总提名党员数
        if ($sums) {
            $zdps = $sums->zdps;
            $zdys = $sums->zdys;
        }
        $count = DB::table($relation_table)->where('name', $relation_row->name)->count();
        $is_same = $count > 1 ? 1 : 0; # 是否有多个同名同月的

        if($relation_table == 'ddb_lw'){
            $count_dwdm_arr = DB::select(DB::raw("select dwdm,count(*) from {$relation_table} where name = '{$relation_row->name}' group by dwdm;"));
            # 这是这个姓名和出生年月的第一个上传信息为主要记录
            DB::table($relation_table)->where('name', $relation_row->name)->update(['is_main' => 0, 'is_same' => $is_same, 'zdps' => $zdps, 'zdys' => $zdys, 'xjdws' => count($count_dwdm_arr)]);
        }else{
            # 这是这个姓名和出生年月的第一个上传信息为主要记录
            DB::table($relation_table)->where('name', $relation_row->name)->update(['is_main' => 0, 'is_same' => $is_same, 'zdps' => $zdps, 'zdys' => $zdys]);
        }




        $first_row = DB::table($relation_table)->where('name', $relation_row->name)->orderBy('created_at', 'asc')->orderBy('id', 'asc')->first();
        if ($first_row) {
            DB::table($relation_table)->where('id', $first_row->id)->update(['is_main' => 1]);
        }
    }

    /**
     * 处理修改的党代表数据
     */
    public function save($inputs, Model $model = null)
    {
        if (isset($inputs['_inline_edit_']) && $inputs['_inline_edit_']) {
            # 行内编辑
            return $this->dealInlineData($inputs, $model);
        }

        $inputs = collect($inputs)->except(['_token', '_method', '_previous_'])->all();

        $table = $model->getTable();
        $modelClass = get_class($model);
        $is_edit = $model->id ? true : false;
        
        if (!$is_edit) {
            $dwdm = $this->admin_user->ddb_dwdm;
            if (!$dwdm) {
                $this->error('您没有设置单位');
            }

            # 新增
            if ($modelClass::query()->where('name', $inputs['name'])->where('dwdm', $dwdm)->exists()) {
                $this->error('该人员已经存在');
            }
        } else {
            # 修改
            if ($modelClass::query()->where('name', $inputs['name'])->where('dwdm', $model->dwdm)->where('id', '<>', $model->id)->exists()) {
                $this->error('该人员已经存在');
            }
            $dwdm = $model->dwdm;
        }
        $filter_data = collect($inputs)->only($modelClass::$edit_fields)->filter()->all(); # 这里的数据用来做表单验证
        $errors = $modelClass::validators($filter_data);
        if ($errors) {
            $inputs['is_error'] = 1;
            $inputs['errors'] = json_encode($errors);
            $this->error(implode("<br/>", $errors));
        }
        $inputs['is_error'] = 0;
        $inputs['errors'] = json_encode([]);
        $inputs['updated_by_gid'] = $this->admin_user->gid;
        $inputs['updated_at'] = date("Y-m-d H:i:s");
        if (!$is_edit) {
            # 新增
            $inputs['dwdm'] = $dwdm;
            $inputs['dwmc'] = Department::query()->where('dwdm', $dwdm)->value('dwmc');
            $inputs['created_by_gid'] = $this->admin_user->gid;
            $model = $modelClass::create($inputs);
            $this->updateDdbMainRow($model, $table);
        } else {
            $orign_name = $model->name; # 原来的姓名

            # 修改
            $model->update($inputs);

            # 同步更新总提名数量
            $this->updateDdbMainRow($model, $table);

            # 如果修改了姓名或者出生日期
            if ($orign_name != $inputs['name']) {
                $origin_model = $modelClass::query()->where('name', $orign_name)->first();
                if ($origin_model) {
                    $this->updateDdbMainRow($origin_model, $table);
                }
            }

        }
    }

    /**
     * 信息行内编辑
     */
    public function dealInlineData($inputs, Model $model)
    {
        $table = $model->getTable();
        $modelClass = get_class($model);
        $filter_data = collect($inputs)->only($modelClass::$edit_fields)->all();
        $field = '';
        foreach(collect($filter_data)->keys() as $key) {
            $field = $key ? $key : '';
        }
        if (!$field) {
            $this->error('此处无法修改，请使用编辑按钮进行数据修改');
        }
        if (in_array($field, ['name'])) {
            $name = $field == 'name' ? $filter_data['name'] : $model->name;
            // $dzb = $field == 'dzb' ? $filter_data['dzb'] : $model->dzb;
            # 修改
            if ($modelClass::query()->where('name', $name)->where('dwdm', $model->dwdm)->where('id', '<>', $model->id)->exists()) {
                $this->error('该人员已经存在');
            }
        }

        $errors = $modelClass::validatorsFoInline($field, collect($filter_data)->filter()->all(), $model->toArray());
        if ($errors) {
            $this->error(implode("<br/>", $errors));
        }
        $update_data = $filter_data;
        $update_data['is_error'] = 0;
        $update_data['errors'] = json_encode([]);
        $inputs['updated_by_gid'] = $this->admin_user->gid;
        $inputs['updated_at'] = date("Y-m-d H:i:s");

        $orign_name = $model->name; # 原来的姓名

        $model->update($update_data);
        if (in_array($field, ['name', 'dys', 'dps'])) {
            $this->updateDdbMainRow($model, $table);
        }

        if (in_array($field, ['name'])) {
            $name = $model->name;
            # 如果修改了姓名或者出生日期
            if ($orign_name != $name) {
                $origin_model = $modelClass::query()->where('name', $orign_name)->first();
                if ($origin_model) {
                    $this->updateDdbMainRow($origin_model, $table);
                }
            }
        }
    }
}